﻿Imports System.IO
Imports System.Text
Imports Microsoft
Imports System.Data.SqlClient
Imports System.Data.Sql
Imports qLDataLayer
Imports Microsoft.ApplicationBlocks.Data
Imports Microsoft.SqlServer.Management.Smo
Imports System.Reflection
Imports System.Collections.Specialized
Imports System.Data.OleDb
Imports System.Threading
Imports ICSharpCode.SharpZipLib.Checksums
Imports ICSharpCode.SharpZipLib.Zip
Imports ICSharpCode.SharpZipLib.GZip

Public Class frmBackupData

    Private sConnectString As String = ""
    Private sFileName As String = ""
    Private BackupPath As String = GetCurrentPath() + "BackupTemp\"
    Private oServer As SQLDMO.SQLServer2
    Dim oBCPExport As New SQLDMO.BulkCopy2

#Region "Function & Sub"
    'Data Source=PC1105wyt;Initial Catalog=QuanLyNhanSu_TKSVN;Persist Security Info=True;User ID=sa;Password=thangphuong

    Private Function GetCurrentPath() As String
        Dim sPath As String = System.Reflection.Assembly.GetExecutingAssembly.Location
        Dim n As Integer = InStrRev(sPath, "\")
        If (n > 0) Then
            sPath = Mid(sPath, 1, n)
        End If
        Return sPath
    End Function

    Private Function GetStringConnect() As String
        sConnectString = "Data Source=" & txtServerName.Text & ";Initial Catalog=" & txtDatabaseName.Text & ";Persist Security Info=True;User ID=" & txtUserName.Text & ";Password=" & txtPassword.Text
        Return sConnectString
    End Function

    Private Function ConnectToDatabaseAndRefesh(ByVal sServerName As String, ByVal sDatabaseName As String, ByVal sUserName As String, ByVal sPassword As String) As Boolean
        oServer = New SQLDMO.SQLServer2
        oServer.EnableBcp = True
        oServer.Connect(sServerName, sUserName, sPassword)
        oDatabase = Nothing
        Try
            oDatabase = oServer.Databases.Item(sDatabaseName)
            oDatabase.DBOption.SelectIntoBulkCopy = True
            Return True
        Catch ex As Exception
            MessageBox.Show(ex.ToString, "Thông báo lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Return False
        End Try
    End Function

    Private Function GetTablesName(ByVal sServerName As String, ByVal sDatabaseName As String, ByVal sUserName As String, ByVal sPassword As String, ByVal sNoOfRows As String) As DataTable
        Dim oDataTable As New DataTable
        Me.ConnectToDatabaseAndRefesh(sServerName, sDatabaseName, sUserName, sPassword)
        oDataTable = New DataTable
        oDataTable.Columns.Add("TableName", "".GetType)
        oDataTable.Columns.Add("Select", True.GetType)
        oDataTable.Columns.Add("TotalRows", "".GetType)
        oDataTable.Columns.Add("Condition", "".GetType)
        oDataTable.Columns.Add("BCPCommand", "".GetType)
        For i As Integer = 1 To oDatabase.Tables.Count
            If Not oDatabase.Tables.Item(i).SystemObject Then
                Dim sBCPCommand As String = ""
                oDataTable.Rows.Add(New Object() {oDatabase.Tables.Item(i).Name, True, sNoOfRows, "", sBCPCommand})
            End If
        Next
        oDataTable.TableName = "Tables"
        Return oDataTable
    End Function

    Private Function GetViewsName(ByVal sServerName As String, ByVal sDatabaseName As String, ByVal sUserName As String, ByVal sPassword As String) As DataTable
        Dim oDataTable As New DataTable
        Me.ConnectToDatabaseAndRefesh(sServerName, sDatabaseName, sUserName, sPassword)
        oDataTable.Columns.Add("ViewName", "".GetType)
        oDataTable.Columns.Add("Select", True.GetType)
        For i As Integer = 1 To oDatabase.Views.Count
            If Not oDatabase.Views.Item(i).SystemObject Then
                oDataTable.Rows.Add(New Object() {oDatabase.Views.Item(i).Name, True})
            End If
        Next
        oDataTable.TableName = "Views"
        Return oDataTable
    End Function

    Private Function GetSPNsName(ByVal sServerName As String, ByVal sDatabaseName As String, ByVal sUserName As String, ByVal sPassword As String) As DataTable
        Dim oDataTable As New DataTable
        Me.ConnectToDatabaseAndRefesh(sServerName, sDatabaseName, sUserName, sPassword)
        oDataTable.Columns.Add("SPName", "".GetType)
        oDataTable.Columns.Add("Select", True.GetType)
        For i As Integer = 1 To oDatabase.StoredProcedures.Count
            If Not oDatabase.StoredProcedures.Item(i).SystemObject Then
                oDataTable.Rows.Add(New Object() {oDatabase.StoredProcedures.Item(i).Name, True})
            End If
        Next
        Return oDataTable
    End Function

    Private Function GetUDFsName(ByVal sServerName As String, ByVal sDatabaseName As String, ByVal sUserName As String, ByVal sPassword As String) As DataTable
        Dim oDataTable As New DataTable
        Me.ConnectToDatabaseAndRefesh(sServerName, sDatabaseName, sUserName, sPassword)
        oDataTable.Columns.Add("UDFName", "".GetType)
        oDataTable.Columns.Add("Select", True.GetType)
        For i As Integer = 1 To oDatabase.UserDefinedFunctions.Count
            If Not oDatabase.UserDefinedFunctions.Item(i).SystemObject Then
                oDataTable.Rows.Add(New Object() {oDatabase.UserDefinedFunctions.Item(i).Name, True})
            End If
        Next
        Return oDataTable
    End Function

    Private Function GetUDDsName(ByVal sServerName As String, ByVal sDatabaseName As String, ByVal sUserName As String, ByVal sPassword As String) As DataTable
        Dim oDataTable As New DataTable
        Me.ConnectToDatabaseAndRefesh(sServerName, sDatabaseName, sUserName, sPassword)
        oDataTable.Columns.Add("UDDName", "".GetType)
        oDataTable.Columns.Add("Select", True.GetType)
        For i As Integer = 1 To oDatabase.UserDefinedDatatypes.Count
            oDataTable.Rows.Add(New Object() {oDatabase.StoredProcedures.Item(i).Name, True})
        Next
        Return oDataTable
    End Function

    Private Function GetUserName(ByVal sServerName As String, ByVal sDatabaseName As String, ByVal sUserName As String, ByVal sPassword As String) As DataTable
        Dim oDataTable As New DataTable
        Me.ConnectToDatabaseAndRefesh(sServerName, sDatabaseName, sUserName, sPassword)
        oDataTable.Columns.Add("UserName", "".GetType)
        oDataTable.Columns.Add("Select", True.GetType)
        For i As Integer = 1 To oDatabase.Users.Count
            If Not oDatabase.Users.Item(i).SystemObject Then
                If (oDatabase.Users.Item(i).Name.ToUpper() <> "GUEST" And oDatabase.Users.Item(i).Name.ToUpper() <> "INFORMATION_SCHEMA" And oDatabase.Users.Item(i).Name.ToUpper() <> "SYS") Then
                    oDataTable.Rows.Add(New Object() {oDatabase.Users.Item(i).Name, True})
                End If
            End If
        Next
        Return oDataTable
    End Function

    Private Sub LoadGird()
        With grdTableList.DisplayLayout.Bands(0)
            .Columns("TableName").Width = 150
            .Columns("Select").Width = 100
            .Columns("TotalRows").Width = 150
            .Columns("Condition").Width = 280
            .Columns("BCPCommand").Hidden = True

            .Columns("TableName").Header.Caption = "Tên bảng"
            .Columns("Select").Header.Caption = "Chọn"
            .Columns("TotalRows").Header.Caption = "Tổng số hàng"
            .Columns("Condition").Header.Caption = "Điều kiện"
        End With
        With grdViewList.DisplayLayout.Bands(0)
            .Columns("Select").Width = 150
            .Columns("ViewName").Width = grdViewList.Width - .Columns("Select").Width

            .Columns("ViewName").Header.Caption = "Tên view"
            .Columns("Select").Header.Caption = "Chọn"
        End With
        With grdSPList.DisplayLayout.Bands(0)
            .Columns("Select").Width = 150
            .Columns("SPName").Width = grdSPList.Width - .Columns("Select").Width

            .Columns("SPName").Header.Caption = "Tên thủ tục"
            .Columns("Select").Header.Caption = "Chọn"
        End With
        With grdUDFList.DisplayLayout.Bands(0)
            .Columns("Select").Width = 150
            .Columns("UDFName").Width = grdUDFList.Width - .Columns("Select").Width

            .Columns("UDFName").Header.Caption = "Hàm người dùng tự định nghĩa"
            .Columns("Select").Header.Caption = ""
        End With
        With grdUDDList.DisplayLayout.Bands(0)
            .Columns("Select").Width = 150
            .Columns("UDDName").Width = grdUDDList.Width - .Columns("Select").Width

            .Columns("Select").Header.Caption = "Chọn"
            .Columns("UDDName").Header.Caption = "Kiểu DL người dùng định nghĩa"
        End With
        With grdUserList.DisplayLayout.Bands(0)
            .Columns("Select").Width = 150
            .Columns("UserName").Width = grdUserList.Width - .Columns("Select").Width

            .Columns("UserName").Header.Caption = "Tên người sử dụng"
            .Columns("Select").Header.Caption = "Chọn"
        End With
    End Sub

    Private Sub ConnectToDatabase()
        If (Me.ConnectToDatabaseAndRefesh(txtServerName.Text, txtDatabaseName.Text, txtUserName.Text, txtPassword.Text)) Then
            btnExport.Enabled = True
        End If
        grdTableList.DataSource = Me.GetTablesName(txtServerName.Text, txtDatabaseName.Text, txtUserName.Text, txtPassword.Text, txtNoOfRows.Text)
        grdViewList.DataSource = Me.GetViewsName(txtServerName.Text, txtDatabaseName.Text, txtUserName.Text, txtPassword.Text)
        ProgressBar1.Value = 4
        grdSPList.DataSource = Me.GetSPNsName(txtServerName.Text, txtDatabaseName.Text, txtUserName.Text, txtPassword.Text)
        ProgressBar1.Value = 5
        grdUDFList.DataSource = Me.GetUDFsName(txtServerName.Text, txtDatabaseName.Text, txtUserName.Text, txtPassword.Text)
        ProgressBar1.Value = 6
        grdUDDList.DataSource = Me.GetUDDsName(txtServerName.Text, txtDatabaseName.Text, txtUserName.Text, txtPassword.Text)
        ProgressBar1.Value = 6
        grdUserList.DataSource = Me.GetUserName(txtServerName.Text, txtDatabaseName.Text, txtUserName.Text, txtPassword.Text)
        ProgressBar1.Value = 8
        Me.LoadGird()
    End Sub

    Private Sub LoadSettingsFrom(ByVal sFileName As String)
        Dim oDataset As New DataSet
        If Not My.Computer.FileSystem.FileExists(sFileName) Then
            Exit Sub
        End If
        If (My.Computer.FileSystem.FileExists(sFileName)) Then
            oDataset.ReadXml(sFileName)
            Dim oDatatable As DataTable
            'Load Preset combo box
            oDatatable = oDataset.Tables("Preset")

            'Fill default values for server, database etc.
            oDatatable = oDataset.Tables(0)
            If oDatatable.Rows.Count > 0 Then
                txtServerName.Text = oDatatable.Rows(0)("Server")
                txtDatabaseName.Text = oDatatable.Rows(0)("Database")
                txtUserName.Text = oDatatable.Rows(0)("UserName")
                txtPassword.Text = oDatatable.Rows(0)("Password")
            Else
                txtServerName.Text = ""
                txtDatabaseName.Text = ""
                txtUserName.Text = ""
                txtPassword.Text = ""
            End If
        End If
    End Sub

    Private Sub SaveSettingsAs(ByVal sFileName As String)

        Dim oTable As New DataTable
        Dim oDataset As New DataSet
        'Save settings for database, server etc
        oTable.Columns.Add("Server", "".GetType)
        oTable.Columns.Add("Database", "".GetType)
        oTable.Columns.Add("UserName", "".GetType)
        oTable.Columns.Add("Password", "".GetType)
        oTable.Columns.Add("chkData", True.GetType)
        oTable.Columns.Add("chkStructure", True.GetType)
        oTable.Columns.Add("NoOfRows", "".GetType)
        'DT.Columns.Add("BackupDir", "".GetType)
        oTable.Rows.Add(New Object() {txtServerName.Text, txtDatabaseName.Text, txtUserName.Text, txtPassword.Text, chkData.Checked, chkStructure.Checked, txtNoOfRows.Text})
        oTable.TableName = "DefaultValues"
        oDataset.Tables.Add(oTable)

        Dim oDTPresetNew As New DataTable
        oDTPresetNew.TableName = "Preset"
        oDTPresetNew.Columns.Add("Server", "".GetType())
        oDTPresetNew.Columns.Add("Database", "".GetType())
        oDTPresetNew.Columns.Add("UserName", "".GetType())
        oDTPresetNew.Columns.Add("Password", "".GetType())

        Dim DTPreset As DataTable
        Dim DSPreset As New DataSet
        'Kiểm tra sự tồn tại của file
        If (My.Computer.FileSystem.FileExists(sFileName)) Then
            DSPreset.ReadXml(sFileName)
            DTPreset = DSPreset.Tables("Preset")
        End If
        If (Not IsNothing(DTPreset)) Then
            oDTPresetNew = DTPreset.Copy()
        End If

        Dim i As Integer
        Dim bFound As Boolean = False
        For i = 0 To oDTPresetNew.Rows.Count - 1
            If oDTPresetNew.Rows(i)("Server").ToString().ToUpper() = txtServerName.Text.ToUpper() Then
                bFound = True
                oDTPresetNew.Rows(i)("UserName") = txtUserName.Text
                oDTPresetNew.Rows(i)("Password") = txtPassword.Text
            End If
        Next

        If (Not bFound) Then
            If (txtServerName.Text.Trim() <> "") Then
                oDTPresetNew.Rows.Add(New Object() {txtServerName.Text, txtDatabaseName.Text, txtUserName.Text, txtPassword.Text})
            End If
        End If
        oDataset.Tables.Add(oDTPresetNew)
        oDataset.WriteXml(sFileName)
        oDataset.Tables.Clear()
    End Sub

    Private Function AskSaveAsFile() As String
        Dim fileD As New SaveFileDialog
        fileD.Filter = "Tệp tin nén | *.zip"
        If (fileD.ShowDialog = Windows.Forms.DialogResult.OK) Then
            Return fileD.FileName
        Else
            Return ""
        End If
    End Function

    Private Function GenerateScript(ByVal sServerName As String, ByVal sDatabaseName As String, ByVal sUserName As String, ByVal sPassword As String, ByVal pObjectType As String, ByVal pObjectName As String) As String
        Dim sSQL As String = ""
        If (pObjectType.ToLower() = "user") Then
            If Not IsNothing(oDatabase.Users.Item(pObjectName)) Then
                sSQL = oDatabase.Users.Item(pObjectName).Script(SQLDMO.SQLDMO_SCRIPT_TYPE.SQLDMOScript_Drops)
                sSQL = sSQL + oDatabase.Users.Item(pObjectName).Script()
            End If
        Else
            If Not IsNothing(oDatabase.GetObjectByName(pObjectName)) Then

                sSQL = oDatabase.GetObjectByName(pObjectName).Script(SQLDMO.SQLDMO_SCRIPT_TYPE.SQLDMOScript_Drops)
                sSQL = sSQL + oDatabase.GetObjectByName(pObjectName).Script()
            End If
        End If
        Return sSQL
    End Function

    Private Sub ExportData(ByVal sServerName As String, ByVal sDatabaseName As String, ByVal sUserName As String, ByVal sPassword As String, ByVal sTableName As String, ByVal sCondition As String, ByVal sTotalRows As String, ByVal sBackUpDir As String)
        oBCPExport.IncludeIdentityValues = True
        oBCPExport.DataFilePath = sBackUpDir + sTableName + ".dat"
        oBCPExport.DataFileType = SQLDMO.SQLDMO_DATAFILE_TYPE.SQLDMODataFile_NativeFormat
        oBCPExport.UseExistingConnection = True
        If InStr(sTotalRows, "TOP 100 PERCENT *", CompareMethod.Text) > 0 And Trim(sCondition = "") Then
            oDatabase.Tables.Item(sTableName).ExportData(oBCPExport)
        Else
            Dim sSelectCommand As String = "select " + sTotalRows + " from " + sDatabaseName + ".." + sTableName
            If Trim(sCondition) <> "" Then
                sSelectCommand += " WHERE " + sCondition
            End If
            Try
                oDatabase.ExecuteImmediate("drop view Temp_View_For_Backup_001", SQLDMO.SQLDMO_EXEC_TYPE.SQLDMOExec_Default)
            Catch ex As Exception
                MessageBox.Show(ex.ToString, "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error)
            End Try
            oDatabase.ExecuteImmediate("create view Temp_View_For_Backup_001 as " + sSelectCommand, SQLDMO.SQLDMO_EXEC_TYPE.SQLDMOExec_Default)
            oDatabase.Views.Refresh()
            oDatabase.Views.Item("Temp_View_For_Backup_001").ExportData(oBCPExport)
            Try
                oDatabase.ExecuteImmediate("drop view Temp_View_For_Backup_001", SQLDMO.SQLDMO_EXEC_TYPE.SQLDMOExec_Default)
            Catch ex As Exception
                MessageBox.Show(ex.ToString, "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error)
            End Try
        End If
        If My.Computer.FileSystem.GetFileInfo(oBCPExport.DataFilePath).Length <= 0 Then
            My.Computer.FileSystem.DeleteFile(oBCPExport.DataFilePath)
        End If
    End Sub

    Private Function GetFileNameFromFullPath(ByVal sPath As String) As String
        Dim n As Integer = InStrRev(sPath, "\")
        If n > 0 Then
            Return Trim(Mid(sPath, n + 1, Len(sPath)))
        End If
        Return sPath
    End Function

    Private Sub ZipFiles(ByVal sSourceDir As String, ByVal sFileName As String)

        Dim astrFileNames() As String = Directory.GetFiles(sSourceDir)
        Dim objCrc32 As New Crc32()
        Dim strmZipOutputStream As ZipOutputStream

        strmZipOutputStream = New ZipOutputStream(File.Create((sFileName)))
        strmZipOutputStream.SetLevel(6)

        Dim strFile As String

        For Each strFile In astrFileNames

            Dim strmFile As FileStream = File.OpenRead(strFile)
            Dim abyBuffer(strmFile.Length - 1) As Byte

            strmFile.Read(abyBuffer, 0, abyBuffer.Length)

            Dim objZipEntry As ZipEntry = New ZipEntry(Me.GetFileNameFromFullPath(strFile))

            objZipEntry.DateTime = DateTime.Now
            objZipEntry.Size = strmFile.Length

            strmFile.Close()
            objCrc32.Reset()
            objCrc32.Update(abyBuffer)
            objZipEntry.Crc = objCrc32.Value
            strmZipOutputStream.PutNextEntry(objZipEntry)
            strmZipOutputStream.Write(abyBuffer, 0, abyBuffer.Length)

        Next
        strmZipOutputStream.Finish()
        strmZipOutputStream.Close()
    End Sub

    'Hàm tạo tệp tin
    Private Sub GenerateFiles(ByRef DTScripts As DataTable, ByRef dg As Infragistics.Win.UltraWinGrid.UltraGrid, ByVal bExportData As Boolean, ByVal pObjectType As String, ByVal bGenerateScripts As Boolean)
        If Not IsNothing(dg.DataSource) Then
            Dim DT As DataTable = CType(dg.DataSource, DataTable)  'Gán dữ liệu của bảng mới bằng dữ liệu của bảng cần sao lưu dữ liệu 
            Dim i As Integer
            ProgressBar1.Minimum = 0
            ProgressBar1.Maximum = DT.Rows.Count
            ProgressBar1.Value = 0
            For i = 0 To DT.Rows.Count - 1
                If DT.Rows(i)("Select") = True Then
                    Dim ObjectName As String = CStr(DT.Rows(i)(pObjectType + "NAME"))
                    lbStatus2.Text = "" + ObjectName + ""
                    If bGenerateScripts Then
                        Dim sSQL As String = Me.GenerateScript(txtServerName.Text, txtDatabaseName.Text, txtUserName.Text, txtPassword.Text, pObjectType, ObjectName)
                        DTScripts.Rows.Add(New Object() {DT.Rows(i)(pObjectType + "NAME"), pObjectType, sSQL})
                    End If
                    If bExportData Then
                        Me.ExportData(txtServerName.Text, txtDatabaseName.Text, txtUserName.Text, txtPassword.Text, DT.Rows(i)(pObjectType + "NAME"), DT.Rows(i)("Condition"), DT.Rows(i)("TotalRows"), BackupPath)
                    End If
                End If
                ProgressBar1.Value = i
            Next
            DTScripts.TableName = "SQLScripts"
            DTScripts.WriteXml(BackupPath + "CSDLSaoLuu.xml")
        End If
    End Sub

    Private Sub ExportDatabase()
        If My.Computer.FileSystem.DirectoryExists(BackupPath) Then
            My.Computer.FileSystem.DeleteDirectory(BackupPath, FileIO.DeleteDirectoryOption.DeleteAllContents)
        ElseIf Not My.Computer.FileSystem.DirectoryExists(BackupPath) Then
            My.Computer.FileSystem.CreateDirectory(BackupPath)
        End If
        Dim oDtScripts As New DataTable 'Tạo bảng dữ liệu lưu : tên , kiểu dữ liệu của đối tượng , lệnh sql
        oDtScripts.Columns.Add("ObjectName", "".GetType)
        oDtScripts.Columns.Add("ObjectType", "".GetType)
        oDtScripts.Columns.Add("ScriptSQL", "".GetType)
        'lbStatus1.Text = "Xuất bảng : "
        GenerateFiles(oDtScripts, grdTableList, chkData.Checked, "table", chkStructure.Checked)
        'lbStatus1.Text = "Xuất views : "
        GenerateFiles(oDtScripts, grdViewList, False, "view", chkStructure.Checked)
        'lbStatus1.Text = "Xuất thủ tục : "
        GenerateFiles(oDtScripts, grdSPList, False, "sp", chkStructure.Checked)
        'lbStatus1.Text = "Xuất hàm người dùng định nghĩa : "
        GenerateFiles(oDtScripts, grdUDFList, False, "UDF", chkStructure.Checked)
        'lbStatus1.Text = "Xuất kiểu DL người dùng định nghĩa : "
        GenerateFiles(oDtScripts, grdUDDList, False, "UDD", chkStructure.Checked)
        'lbStatus1.Text = "Xuất người dùng : "
        GenerateFiles(oDtScripts, grdUserList, False, "User", chkStructure.Checked)
        Me.ZipFiles(BackupPath, sFileName)
        My.Computer.FileSystem.DeleteDirectory(BackupPath, FileIO.DeleteDirectoryOption.DeleteAllContents)
        MessageBox.Show("Đã sao lưu CSDL thành công", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information)
    End Sub

#End Region

    Private Sub frmBackupData_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Try
            lbStatus1.Visible = False
            lbStatus2.Visible = False
            ProgressBar1.Visible = False
            LoadSettingsFrom(My.Application.Info.DirectoryPath + "\DefaultValues.backupsettings")
        Catch ex As Exception
            MessageBox.Show(ex.ToString, "Thông báo lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

    Private Sub btnLogin_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnConnect.Click
        Try
            Dim oConn As SqlConnection = New SqlConnection(GetStringConnect)
            Try
                oConn.Open()
                oConn.Close()
            Catch
                Throw
            End Try
            ProgressBar1.Visible = True
            ProgressBar1.Maximum = 8
            ProgressBar1.Value = 1
            Me.Refresh()
            ConnectToDatabase()
            SaveSettingsAs(My.Application.Info.DirectoryPath + "\DefaultValues.backupsettings")
            ProgressBar1.Visible = False
        Catch ex As Exception
            MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Stop)
        Finally
        End Try
    End Sub

    Private Sub btnExport_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnExport.Click
        'Kết nối tới CSDL
        ConnectToDatabaseAndRefesh(txtServerName.Text, txtDatabaseName.Text, txtUserName.Text, txtPassword.Text)
        'Kiểm tra chọn kiểu sao lưu dữ liệu hay chưa
        If chkData.Checked = False And chkStructure.Checked = False Then
            MessageBox.Show("Bạn phải chọn sao lưu cấu trúc hay sao lưu dữ liệu", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End If
        lbStatus1.Visible = True
        'lbStatus2.Visible = True
        ProgressBar1.Visible = True
        ProgressBar1.Maximum = 8
        ProgressBar1.Value = 1
        Me.Refresh()
        'Mở hộp thoại để chọn nơi lưu
        sFileName = AskSaveAsFile()
        Try
            If sFileName <> "" Then
                'Gọi hàm xuất dữ liệu
                ExportDatabase()
            End If
        Catch ex As Exception
            MessageBox.Show(ex.ToString, "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

End Class
